package com.study.service.impl;

import com.study.exception.CustomException;
import com.study.mapper.UsersMapper;
import com.study.pojo.Users;
import com.study.service.UsersService;

import com.study.utils.JwtUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UsersServiceImpi  implements UsersService {
    @Override
    public String getCode() {
        return "";
    }

    @Resource
    private UsersMapper usersMapper;

    @Override
    public List<Users> selectAll() {
        return usersMapper.selectAll();
    }

    // 注册
    @Override
    public void register(Users users) {
        Users user = usersMapper.findUserByUsername(users.getUsername());
        if (user != null) {
            throw new CustomException("用户名已存在", "400");
        }
        try {
            usersMapper.register(users);
        } catch (Exception e) {
            throw new RuntimeException("注册失败");
        }
    }

    @Override
    public Users findUserByUsername(String username) {
        return usersMapper.findUserByUsername(username);
    }

    @Override
    public String login(Users users) {
        Users user = usersMapper.findUserByUsername(users.getUsername());

        if (user == null) {
            throw new CustomException("用户名不存在", "400");
        }
        if (!user.getPassword().equals(users.getPassword())) {
            throw new CustomException("密码错误", "400");
        }

        // 设置jwt token
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", user.getId());
        claims.put("username", user.getUsername());
        String token = JwtUtil.createToken(claims);
        return token;
    }

    @Override
    public void updateUserInfo(Users users) {
        usersMapper.updateUserInfo(users);
    }
}
